/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package capituseradminstrator.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author pais
 */
public abstract class GenericDaoSer <T, PK extends Serializable> {

public abstract T save (T t);
public abstract List <T> getAll ();

public T persist (T pojo){

    List<T> allObjects = null;
    //Is there any file?
    File file = new File("c:/"+pojo.getClass().getName());
    if (file.exists()){
        //We can get what we saved before...
        allObjects = getAll(pojo.getClass());
    } else{
        allObjects = new ArrayList<T>();
    }
    
    
    //We add serializable object
      allObjects.add(pojo);
      FileOutputStream fos = null;
      ObjectOutputStream out = null;
      try{
            fos = new FileOutputStream(file);
            out = new ObjectOutputStream(fos);
            out.writeObject(allObjects);
            out.close();
          }catch(IOException ex){ex.printStackTrace();
          }
      return pojo;
}


public List<T> getAll (Class clazz){

            FileInputStream fis = null;
            ObjectInputStream ois = null;
            List listReturn = new ArrayList();

        try {
           
            fis = new FileInputStream("c:/" + clazz.getName());
            ois = new ObjectInputStream(fis);
            listReturn = (ArrayList) ois.readObject();
            ois.close();
            
            
        } catch (FileNotFoundException ex) {
            Logger.getLogger(GenericDaoSer.class.getName()).log(Level.SEVERE, null, ex);
        }catch (ClassNotFoundException ex) {
            Logger.getLogger(GenericDaoSer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(GenericDaoSer.class.getName()).log(Level.SEVERE, null, ex);
        }
        return listReturn;
}


}
